# -*- coding: utf-8 -*-
# @Time        :2025/8/18 14:28
# @Author      :文刀水寿
# @File        : xhs_cookie.py
"""
 @Description :
"""
from redis import Redis, ConnectionPool
import configparser
import threading
import os
import sys
from pathlib import Path

project_root = Path(__file__).parent.parent
INI_FILE_NAME = project_root / "Browser" / "xhs_cookies.ini"
print(INI_FILE_NAME)


class RedisClient:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance._init_redis()
        return cls._instance

    def get_all_keys(self, pattern='*'):
        """获取所有匹配模式的key（默认获取所有）"""
        return self.client.keys(pattern)

    def _init_redis(self):

        # 读取配置文件
        config = configparser.ConfigParser()
        config_files = config.read(INI_FILE_NAME)
        # print("++++++++++", config_files)
        # print()
        # 连接池配置（使用直接导入的ConnectionPool）
        pool = ConnectionPool(
            host=config.get('redis', 'host'),
            port=config.getint('redis', 'port'),
            db=config.getint('redis', 'db'),
            password=config.get('redis', 'password') or None,
            decode_responses=config.getboolean('redis', 'decode_responses'),
            max_connections=config.getint('redis', 'max_connections')
        )
        self.client = Redis(connection_pool=pool)

    # 以下方法保持不变...
    def set_value(self, key, value, expire=None):
        """设置键值对（可选过期时间，单位：秒）"""
        self.client.set(key, value, ex=expire)

    def get_value(self, key):
        """获取键对应的值"""
        return self.client.get(key)

    def add_to_list(self, list_key, *values):
        """向列表中添加元素"""
        self.client.rpush(list_key, *values)

    def get_list(self, list_key):
        """获取列表所有元素"""
        return self.client.lrange(list_key, 0, -1)

    def add_to_set(self, set_key, *values):
        """向集合中添加元素（自动去重）"""
        self.client.sadd(set_key, *values)

    def get_set(self, set_key):
        """获取集合所有元素"""
        return self.client.smembers(set_key)

    def close(self):
        """关闭连接池"""
        self.client.close()


# 在文件末尾添加
if __name__ == "__main__":
    # 打印路径
    print("INI文件路径：", INI_FILE_NAME)

    # 检查文件是否存在
    if INI_FILE_NAME.exists():
        print("✅ 文件存在")
    else:
        print("❌ 文件不存在！请检查路径是否正确")
